package com.test.threadTest.bf2;

import java.util.concurrent.CountDownLatch;

/**
 *  线程阻塞__执行
 *  zj: countDownLatch.await() 暂停于当前代码行、等待执行
 *   ####  锁state初始值为 0时表示无锁状态、多个线程可进入 CAS _ tryReleaseShared(arg) --> compareAndSetState 减
 *   protected boolean tryReleaseShared(int releases) {
 *             // Decrement count; signal when transition to zero
 *             for (;;) {
 *                 int c = getState();
 *                 if (c == 0)
 *                     return false;
 *                 int nextc = c-1;
 *                 if (compareAndSetState(c, nextc))
 *                     return nextc == 0;
 *             }
 *         }
 *   ####   LockSupport.unpark(s.thread) --> 所有子线程都执行完成（state=0）时会unpark()主线程，然后主线程会从await()返回，继续执行后续的动作
 */
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch=new CountDownLatch(3);
        new Thread(()->{
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();  //递减

        }).start();

        new Thread(()->{
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();

        }).start();

        new Thread(()->{
            try {
                Thread.sleep(6000);
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        countDownLatch.await(); //阻塞
        System.out.println("执行完毕 ");
    }
}
